﻿using BindTryParseMVC.Models;
using System.ComponentModel.DataAnnotations;

namespace BindTryParseMVC.Validation
{
    /// <summary>
    /// 经典电影特性，接收一个年份
    /// </summary>
    public class ClassicMovieAttribute : ValidationAttribute
    {
        public ClassicMovieAttribute(int year)
        {
            Year = year;
        }

        public int Year { get; }

        public string GetErrorMessage() => $"Classic movies must have a release year no later than {Year}.";

        /// <summary>
        /// 验证逻辑
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            //前端传递过来的数据 如果数据绑定到Movie对象后它的 Gener 是 Classic 并且它的 发布年份大于特性中的年份验证失败，否则验证成功。
            var movie = (Movie)validationContext.ObjectInstance;
            var releaseYear = ((DateTime)value!).Year;
            if (movie.Gener == Gener.Classic && releaseYear > Year)
            {
                return new ValidationResult(GetErrorMessage());
            }
            return ValidationResult.Success;
        }
    }
}
